
package android.com.app;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.location.Location;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.ToneGenerator;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.database.Cursor;

public class aPics extends Activity {    
    private Preview mPreview;
    //private Context mContext;
    private boolean gFocussed = false;
    private boolean gCameraPressed= false;
    private LocationHandler mLocationHandler = new LocationHandler(); 
    private LocationManager mLocMan;
    
    @Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.gc();
        //call GPS location manager to get the data from the GPS
        mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,1,(float)1.0, mLocationHandler);
        
        // Hide the window title.
        requestWindowFeature(Window.FEATURE_NO_TITLE);
    
        // Create our Preview view and set it as the content of our activity.
        mPreview = new Preview(this);
        setContentView(mPreview);
        
    }
    protected void onPause() {
    	mLocMan.removeUpdates(mLocationHandler);
    	super.onPause();
    	
    }
    protected void onDestroy(){
    	super.onDestroy();
    }
    
    protected void onResume(){
    	super.onResume();
    	mPreview = new Preview(this);
        setContentView(mPreview);	
    }
    
    /* Menu to the application
     */
    public static final int Menu1 = Menu.FIRST + 1;
 
    
    /* create the menu items 
     */
    public void populateMenu(Menu menu) {
     	@SuppressWarnings("unused")
		MenuItem item1 = menu.add(0, Menu1, 0, "Open Gallery");
    }
    
    /* hook into menu button for activity
     */
    
    public boolean onCreateOptionsMenu(Menu menu) {
      populateMenu(menu);
      return super.onCreateOptionsMenu(menu);
    }

    /* when menu button option selected */
    public boolean onOptionsItemSelected(MenuItem item) {
      return applyMenuChoice(item) || super.onOptionsItemSelected(item);
    }
    /* respond to menu item selection */
    public boolean applyMenuChoice(MenuItem item) {
      switch (item.getItemId()) {
        case Menu1: 
        // go to gallery	
       	Intent i = new Intent();
    	i.setClass(this,thumbviewer.class);
    	startActivity(i);
    	return true;
      }
      return false;
    }   
    
    public boolean onKeyDown(int keyCode, KeyEvent event)  
    {    
    	if (keyCode == KeyEvent.KEYCODE_BACK) {  
	    	//Log.v("1","Key back pressed");
    		return super.onKeyDown(keyCode, event);  
	    } 
    	if (keyCode == KeyEvent.KEYCODE_CAMERA) {
	    	Log.v("1","Key camera pressed");
	    	if (event.getRepeatCount() == 0) {
	    	try {
	    	if(gFocussed){	
	    		mPreview.mCamera.takePicture(mShutterCallback,mPictureCallbackRaw,mPictureCallbackJpeg);  
	    	}else if(!gFocussed){
	    		gCameraPressed = true;
	    		mPreview.mCamera.autoFocus(cb);
	    	}
	    	}catch(Exception e) {
	    		Log.i("Exc",e.toString());
	    	}
	    	}
	    		return true;
	    }
    	if (keyCode == KeyEvent.KEYCODE_FOCUS){
    		try {
    		if (event.getRepeatCount() == 0) {
    			Log.v("2","Key focus pressed");
	    		if(!gFocussed)
	    			mPreview.mCamera.autoFocus(cb);
    		}
    		}catch(Exception e) {
	    		Log.i("Exc",e.toString());
	    	}
    		return true;
    	}
    	return false;  
    } 
    public boolean onKeyUp(int keyCode, KeyEvent event) {
    	   switch (keyCode) {
    	        case KeyEvent.KEYCODE_FOCUS:
    	        	gFocussed=false;
    	        return true;
    	   }
         return false;
    }
    
    Camera.PictureCallback mPictureCallbackRaw = new Camera.PictureCallback() {  
		
		public void onPictureTaken(byte[] data, Camera c) {  
		// Log.i(getClass().getSimpleName(), "PICTURE CALLBACK RAW: " + data);  
		 //mPreview.mCamera.startPreview();  
		}
	};  
	
	Camera.PictureCallback mPictureCallbackJpeg= new Camera.PictureCallback() {  
		
		public void onPictureTaken(byte[] data, Camera c) {
			Log.i(getClass().getSimpleName(), "PICTURE CALLBACK JPEG: data.length = " + data);
					
			String filename = String.valueOf(System.currentTimeMillis()) ;  
			
			//images
			ContentValues values = new ContentValues();
			values.put(Images.Media.TITLE, filename);
			//values.put(Images.Media.DATA, filename);
			values.put(Images.Media.MIME_TYPE, "image/jpeg");
			Log.i("OnPictureTaken","filenam:"+filename);
			
			//thumbnails 
			
			//GPS location 
			Location location = mLocMan.getLastKnownLocation("gps");
	 		if(location != null)
	 		{
	 		   values.put(Images.Media.LATITUDE, location.getLatitude());
	 		   values.put(Images.Media.LONGITUDE, location.getLongitude());
			}else{
				Log.w("GPS NULL "," Check");
			}
	 		
			Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
			
			String[] stringarray = uri.toString().split("/");
			Integer count = stringarray.length;
			String id = stringarray[count-1];
			Log.i("CHK",id);
			ContentValues thumbvalues = new ContentValues();
			thumbvalues.put(Images.Thumbnails.IMAGE_ID, id);
			
			Uri thumbUri = getContentResolver().insert(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,thumbvalues);
 		    
			String[] thumbstringarray = thumbUri.toString().split("/");
			Integer thumbcount = thumbstringarray.length;
			String thumbid = thumbstringarray[thumbcount-1];
			
			System.gc();
			try{
				Bitmap sourceBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
				Log.i("OnPictureTaken",uri.toString());

 		   
 		    	//Now get a handle to the file for that record, and save the data into it.
 		    	// sourceBitmap is a Bitmap object representing the file to save to the database.
 		    	
 		    	//thumbnails code
 		    	OutputStream outStreamthumb = getContentResolver().openOutputStream(thumbUri);
 		    	//FileOutputStream fileoutstream = new FileOutputStream("/sdcard/dcim/Camera/"+filename+".jpg");
 		    	
 		    	OutputStream outStream = getContentResolver().openOutputStream(uri);
 		    	//String path = Media.insertImage(getContentResolver(),sourceBitmap,filename,"");
 		    	
 		    	sourceBitmap.compress(Bitmap.CompressFormat.JPEG, 15, outStreamthumb);
 		    	
 		    	//outStreamthumb.write(data);
 		    	outStream.write(data);
 		    	outStream.close();	
 		    	
 		    	//outStreamthumb.flush();
 		    	outStreamthumb.close();
 		    	//sourceBitmap.recycle();
 		    	//System.gc();
 		    	
 		    	Intent i = new Intent();
 		    	i.setClass(getBaseContext(), imageviewer.class);
 		    	//t.setText("select"+imgList.get(selectedIndex));
 		    	
 		    	i.putExtra("ImageData",thumbid); //ID of the image
 		    	if(location != null){
 		    		i.putExtra("GeoPoint",location.getLatitude()+","+ location.getLongitude());
 		    	}
 		    	else{
 		    		i.putExtra("GeoPoint","0.0"+","+"0.0");
 		    	}
 		    	String path = getImagePath(uri);
 		    	String thumbpath = getThumbImagePath(thumbUri);
 		    	
 		    	//MediaScannerNotifier mNot = new MediaScannerNotifier(mPreview.getContext(),path,"image/jpeg");
 		    	MediaScannerNotifier mthumbNot = new MediaScannerNotifier(mPreview.getContext(),thumbpath,"image/jpeg");
 		    	i.putExtra("Title",path);
 		    	startActivity(i);	
	 		} catch (FileNotFoundException fne) {
	 		    Log.e("writing and scanning image ",fne.toString());
	 		    fne.printStackTrace();
	 		    mPreview.mCamera.startPreview();
	 		}
	 		catch(IOException ioe){
	 		   Log.e("writing and scanning image ",ioe.toString());
	 		   ioe.printStackTrace();
	 		   mPreview.mCamera.startPreview();
	 		}
	 		catch(Exception e){
	 			
	 		}
		}  
	};
		  
	Camera.ShutterCallback mShutterCallback = new Camera.ShutterCallback() {
		public void onShutter() {  
			Log.i(getClass().getSimpleName(), "SHUTTER CALLBACK");  
			}  
	};	
	Camera.AutoFocusCallback cb = new Camera.AutoFocusCallback(){
		public void onAutoFocus(boolean success,Camera c){	
			 if (success) {
				
				ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_SYSTEM, 100);
                if (tg != null)
                	tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
                gFocussed=true;
                try {
                if(gCameraPressed){
                	mPreview.mCamera.takePicture(mShutterCallback,mPictureCallbackRaw,mPictureCallbackJpeg);
				}
			  }catch(Exception e) {
				  Log.i("Exc",e.toString());
			  }
			 }
			 else{
				ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_SYSTEM, 100);
	              if (tg != null)
	                	tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
	                
	                
				 try {
		                if(gCameraPressed){
		                	mPreview.mCamera.takePicture(mShutterCallback,mPictureCallbackRaw,mPictureCallbackJpeg);
						}
					  }catch(Exception e) {
						  Log.i("Exc",e.toString());
					  } 
				 
			 }
			 
		}
	};
	public String getImagePath(Uri uri){
		
		Cursor cur = managedQuery(uri, null, null, null, null);
		cur.moveToFirst();
		int column = cur.getColumnIndex(MediaStore.Images.Media.DATA);
		String path = cur.getString(column);
		return path;
	}
	
	public String getThumbImagePath(Uri uri){
		Cursor cur = managedQuery(uri,null,null,null,null);
		cur.moveToFirst();
		int column = cur.getColumnIndex(MediaStore.Images.Thumbnails.DATA);
		String path = cur.getString(column);
		return path;
	}
	
}


class Preview extends SurfaceView implements SurfaceHolder.Callback {
    SurfaceHolder mHolder;
    Camera mCamera;
    
    Preview(Context context) {
        super(context);
        
        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface i	s created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, acquire the camera and tell it where
        // to draw.
    	//Log.i("surface created","--");
        mCamera = Camera.open();
        mCamera.setPreviewDisplay(holder);
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // Surface will be destroyed when we return, so stop the preview.
        // Because the CameraDevice object is not a shared resource, it's very
        // important to release it when the activity is paused.
    	
        mCamera.stopPreview();
        mCamera.release();
        mCamera = null;  
        //Log.i("surface destroyed","--");
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // Now that the size is known, set up the camera parameters and begin
        // the preview.
        Camera.Parameters parameters = mCamera.getParameters();
        parameters.setPreviewSize(w, h);
        mCamera.setParameters(parameters);
        mCamera.startPreview();
        //Log.i("surface changed","--");
    }    
}